<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="format-detection" content="telephone=no"/>
    <meta name="format-detection" content="email=no"/>
    <title>发话题</title>
    <link rel="stylesheet" href="../../css/api.css">
    <link rel="stylesheet" href="../../css/vant.css">
    <link rel="stylesheet" href="../../css/main.css">
    <style>
        .van-cell {
            background: none;
        }

        .publish-img-item {
            position: relative;
        }

        .fileInputContainer {
            width: 1rem;
            height: 1rem;
            background: url('https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/circle/vod_img.png');
            background-repeat: no-repeat;
            background-size: 1rem 1rem;
            position: relative;
        }

        .fileInputContainer > input {
            width: 1rem;
            height: 1rem;
        }

        .fileInput {
            height: .96rem;
            overflow: hidden;
            font-size: 300px;
            position: absolute;
            right: 0;
            top: 0;
            opacity: 0;
            filter: alpha(opacity=0);
            cursor: pointer;
        }

        .fileVideo {
            width: 1rem !important;
            height: 1rem !important;
            position: relative;
            display: block;
        }

        .up-img img, .up-img video {
            object-fit: cover;
        }

        .disable_btn {
            background: #8E8E8E !important;
        }
    </style>
</head>

<body>
<div class="app send-moment" v-cloak>
    <header>
        <div class="flex-x-sb send-moment-header">
            <span class="iconfont goback" @click="back">&#xe66f;</span>
            <div class="title">{{title}}</div>
            <div class="release-btn" :class="{disable_btn:!submitButtonEnable}"
                 v-if="title == '发话题' || title == '举报'" @click="publishNews" >
                发布
            </div>
        </div>
    </header>
    <div class="pt bgFQ">
        <div class="release-textarea">
            <van-field v-model="message" rows="1" autosize type="textarea" placeholder="您想要说点什么呢……"
                       @input="checkCouldPublish"
            ></van-field>
        </div>
        <div class="up-img flex-x-s flex-wrap">
            <div class="container flex-x-s flex-wrap" id="itxst">
                <div class="publish-img-item item flex-x-s"
                     :data-no="(listSortableVideoOrImages.length - 1 === index)?999:index"
                     :class="{'move': (listSortableVideoOrImages.length - 1 !== index)}"
                     v-for="(item,index) in listSortableVideoOrImages" :key="index">
                    <!--视频显示-->
                    <video class="fileVideo" v-if="item.type === 1 && item.videoUrl" id="player"
                           autoplay loop webkit-playsinline playsinline x5-playsinline
                           style="border-radius: 8px" :poster="item.imageUrl" :src="item.videoUrl">
                    </video>
                    <!--图片显示-->
                    <img class="handle" style="border-radius: 8px" v-if="item.type === 0" :src="item.showImagePath ? item.showImagePath : item.imageUrl"
                         alt="">
                    <!--上传操作-->
                    <div v-if="item.type === -1 && listSortableVideoOrImages.length <= 9"
                         class="handle fileInputContainer" @click.stop="doInputLabel">
                        <!-- <input v-if="isUpInput" class="fileInput" type="file" @change="uploadVideoOrImage"> -->
                    </div>
                    <span class="iconfont" v-if="item.type !== -1" @click.stop="sortableRemoveVideoOrImage(index)">
                            <img style="width: .16rem;height: .16rem;" src="https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/delete.png" alt="">
                        </span>
                </div>
            </div>
        </div>



    </div>
    <!-- <input id="input" class="fileInput" type="file"> -->
</div>
<script src="../../script/sortable.js"></script>
<script src="../../script/api.js"></script>
<script src="../../script/flexible.js"></script>
<script src="../../script/fastclick.js"></script>
<script src="../../script/vue.min.js"></script>
<script src="../../script/iconfont.js"></script>
<script src="../../script/vant.min.js"></script>
<script src="../../script/common.js"></script>
<script src="../../script/restful.js"></script>
<script src="../../script/uploadImage.js"></script>
<script src="../../script/businessCommon.js"></script>
<script src="../../script/aliyun-upload-sdk-1.5.0.min.js"></script>
<script src="../../script/es6-promise.min.js"></script>
<script src="../../script/aliyun-oss-sdk-5.3.1.min.js"></script>
<script src="../../script/common_upload_vod.js"></script>
<script src="../../script/lrz.bundle.js"></script>
<script>
    apiready = function () {
        let uploader = null;
        var UIAlbumBrowser = api.require('UIAlbumBrowser');
        vm = new Vue({
            el: '.app',
            data: {
                submitButtonEnable: false,
                message: '',
                listSortableVideoOrImages: [
                    {imageUrl: 'https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/circle/vod_img.png', type: -1, videoId: "", videoUrl: ""}
                ],
                uploadFlag: {image: true, vod: true, vodNumber: 0, imgNumber: 0, vodUploadOver: true},
                title: '发话题',
                isUpInput: false,
                systemSet: {
                    onlineBuyEnabled: false,
                    vodLimitSize: 100,
                    imgLimitSize: 100
                }
            },
            watch:{
                message(val){
                    if(val === '' && this.listSortableVideoOrImages.length === 1){
                        this.submitButtonEnable = false
                    }
                }
            },
            mounted: function () {
                this.initUploadImageModule()
            },
            methods: {
                uploadImageEnd(ret){
                    var index = this.listSortableVideoOrImages.length - 1
                    const media = {
                        imageUrl: ret.data.imagePath,
                        showImagePath: ret.data.showImagePath,
                        type: 0,
                        mediaId: ret.data.resourceId,
                        videoUrl: "",
                        index:index,
                    }
                    this.listSortableVideoOrImages.splice(index, 0, media)
                    vm.submitButtonEnable = true
                },
                uploadVideoEnd(ret, video){
                    var index = this.listSortableVideoOrImages.length - 1
                    const media = {
                        imageUrl: '', 
                        type: 1, 
                        videoId: ret.data,
                        mediaId: ret.data,
                        videoUrl: video.file, 
                        index:index
                    }
                    this.listSortableVideoOrImages.splice(index, 0, media)
                    this.uploadFlag.vodUploadOver = true
                    vm.submitButtonEnable = true
                },
                uploadlibraryEnd(ret, video, type){
                    if(type === 'video'){
                        this.uploadVideoEnd(ret, video)
                    }else{
                        this.uploadImageEnd(ret)
                    }
                },
                doMedia(){
                    var vm = this
                    if( vm.listSortableVideoOrImages.length >= 10){
                        toastMiddle('最多上传9张')
                        return 
                    }
                    api.actionSheet({
                        title: '',
                        cancelTitle: '取消',
                        buttons: ['拍照','摄像', '相册']
                    }, function (ret1, err) {
                        if (ret1.buttonIndex == 1) {
                            commonDoPic(function(ret2){
                                console.log('上传图片返回:',JSON.stringify(ret2));
                                vm.uploadImageEnd(ret2)
                            })
                        } else if (ret1.buttonIndex == 2) {
                            commonDoCamera('TOPIC',function(ret2, video){
                                console.log('上传视频返回:',JSON.stringify(ret2));
                                vm.uploadVideoEnd(ret2, video)
                            })
                        }else if (ret1.buttonIndex == 3) {
                            commonDoLibrary('all' ,'TOPIC',function(ret2, video, type){
                                console.log('上传相册返回:',JSON.stringify(ret2));
                                vm.uploadlibraryEnd(ret2, video, type)
                            }, (10 - vm.listSortableVideoOrImages.length))
                        }
                    })
                },

                doInputLabel() {
                    const resultList = api.hasPermission({
                        list: ['camera', 'photos']
                    });
                    if (resultList[0].granted && resultList[1].granted) {
                        this.doMedia()
                    }else{
                        const ishasCameraOrPhotos = $api.getStorage('ishasCameraOrPhotos');
                        if(!ishasCameraOrPhotos){
                            $api.setStorage('ishasCameraOrPhotos', '1');
                            api.requestPermission({
                                list: ['camera', 'photos'],
                            }, function (ret, err) {
                                if (ret && ret.list && ret.list.length > 0 && ret.list[0].granted && ret.list[1].granted) {
                                    this.doMedia()
                                }
                            });
                        }else{
                            toastMiddle('权限已关闭，请手动打开相机权限')
                        }
                    }
                },

                /**
                 * 检查是否可以发布
                 */
                checkCouldPublish: function () {
                    this.submitButtonEnable = !(this.listSortableVideoOrImages.length === 1 && this.message === "")
                },

                /**
                 * 发布
                 */
                publishNews() {
                    if (!this.submitButtonEnable) {
                        return false;
                    }
                    this.submitButtonEnable = false
                    const vm = this;
                    if (!vm.uploadFlag.vodUploadOver) {
                        toastMiddle("视频还没有上传结束，请耐心等待！")
                        return false
                    }
                    vm.listSortableVideoOrImages.splice(vm.listSortableVideoOrImages.length - 1, 1)
                    const medias = []
                    vm.listSortableVideoOrImages.forEach(img => medias.push(img.mediaId))
                    const param = {content: vm.message, medias: medias}
                    fnPost(interfaces.CONTENT_MODULE.CIRCLE.PUBLISH_NEWS, param, (ret) => {
                            if (ret && ret.code === RESPONSE_OK) {
                                toastMiddle("发布成功!")
                                setTimeout(() => {
                                    api.sendEvent({name: 'refreshAllTopic'});
                                    setTimeout(() => {
                                        api.closeWin()
                                    }, 500)
                                }, 1000)
                            } else {
                                toastBottom(ret ? ret.msg : '');
                            }
                        }
                    );
                },

                back() {
                    api.closeWin();
                },

                //--------------------BEGIN INIT DATA------------------------
                /**
                 * 初始化系统设置
                 */
                initSystemSet: function () {
                    let vm = this
                    common('getSystemSet')({}, function (ret) {
                        vm.systemSet.onlineBuyEnabled = ret.data.onlineBuyEnabled
                        vm.systemSet.vodLimitSize = Number(ret.data.maxVideoSize) / 1024
                        vm.systemSet.imgLimitSize = Number(ret.data.maxImageSize) / 1024
                    })
                },
                //--------------------INIT DATA END------------------------

                //--------------------BEGIN INIT DATA------------------------
                /**
                 * 初始化上传图片拖动模块
                 */
                initUploadImageModule: function () {
                    let vm = this
                    dragDropSortUploadImage('#itxst', (arr) => {
                        let sort = []
                        sort = JSON.parse(JSON.stringify(vm.listSortableVideoOrImages))
                        for (let i = 0; i < arr.length - 1; i++) {
                            vm.listSortableVideoOrImages[i] = sort[arr[i]]
                        }
                    })
                },
                /**
                 * 上传视频和图片
                 */
                uploadVideoOrImage: function (event) {
                    let vm = this;
                    if (event.target.files.length > 0) {
                        // for (let i = 0; i < event.target.files.length; i++) {
                        const file = event.target.files[0];
                        if (!file) {
                            toastMiddle("请先选择需要上传的文件!");
                            return false;
                        }
                        if (file.type.indexOf('image') > -1) {
                            if (!vm.checkUploadFileSize(file, "image")) {
                                return false;
                            }
                            vm.uploadImage(file);
                        } else if (file.type.indexOf('video') > -1) {
                            if (vm.uploadFlag.vodNumber === 3) {
                                vm.uploadFlag.vod = false;
                                toastMiddle("视频到达上限!");
                                return false;
                            }
                            if (!vm.checkUploadFileSize(file, "video")) {
                                return false;
                            }
                            vm.uploadVideo(file);
                        } else {
                            toastMiddle('只能上传图片或者视频');
                            return false;
                        }
                    }
                },
                /**
                 * 上传图片
                 * @param file
                 */
                uploadImage: function (file) {
                    let vm = this
                    vm.submitButtonEnable = false
                    lrz(file)
                    .then(function (rst) {
                        // 处理成功会执行
                        const spliceBase64 = rst.base64.substring(rst.base64.indexOf(',') + 1);
                        fnPostUpData(interfaces.CONTENT_MODULE.UPLOAD_IMAGE, {base64Image: spliceBase64}, true, (ret) => {
                            if (ret && ret.code === RESPONSE_OK) {
                                const media = {
                                    imageUrl: ret.data.imagePath,
                                    type: 0,
                                    mediaId: ret.data.resourceId,
                                    videoUrl: ""
                                }
                                vm.listSortableVideoOrImages.splice(vm.listSortableVideoOrImages.length - 1, 0, media)
                                vm.submitButtonEnable = true
                            } else {
                                toastMiddle(ret ? ret.msg : '');
                            }
                        })
                    })
                    if (vm.listSortableVideoOrImages.length >= 10) {
                        vm.listSortableVideoOrImages.splice(index + 1, 1)
                    }
                },
                /**
                 * 上传视频
                 * @param file
                 */
                uploadVideo: function (file) {
                    let vm = this
                    vm.submitButtonEnable = false
                    const userData = '{"Vod":{}}';
                    if (uploader) {
                        uploader.stopUpload()
                    } else {
                        uploader = createUploader("TOPIC", (ret) => {
                            vm.videoUploadOver(ret)
                        })
                    }
                    const media = {imageUrl: '', type: 1, videoId: '', videoUrl: getObjectURL(file)}
                    vm.$nextTick(() => {
                        vm.listSortableVideoOrImages.splice(vm.listSortableVideoOrImages.length - 1, 0, media)
                    })
                    vm.uploadFlag.vodNumber = vm.uploadFlag.vodNumber + 1
                    if (vm.uploadFlag.vodNumber === 3) {
                        vm.uploadFlag.vod = false
                    }
                    vm.uploadFlag.vodUploadOver = false
                    uploader.addFile(file, null, null, null, userData)
                },
                /**
                 * 视频上传结束操作
                 */
                videoUploadOver: function (uploadInfo) {
                    this.uploadFlag.vodUploadOver = true
                    this.listSortableVideoOrImages[this.listSortableVideoOrImages.length - 2].mediaId = uploadInfo.videoId
                    this.submitButtonEnable = true
                },
                /**
                 * 移除视频或者图像
                 */
                sortableRemoveVideoOrImage: function (index) {
                    // 如果是视频则
                    if (this.listSortableVideoOrImages[index].type === 1) {
                        this.uploadFlag.vodNumber = this.uploadFlag.vodNumber - 1;
                        this.uploadFlag.vod = true;
                    }
                    this.listSortableVideoOrImages.splice(index, 1)
                    this.checkCouldPublish()
                },
                /**
                 * 检查文件大小，如果大于返回false
                 * @param file 待检测文件
                 * @param type 类型
                 */
                checkUploadFileSize: function (file, type) {
                    const fileSize = file.size / 1024 / 1024;
                    console.log('视频大小：', fileSize);
                    if (type === "video") {
                        if (fileSize >= this.systemSet.vodLimitSize) {
                            toastMiddle('视频大小不要超过' + this.systemSet.vodLimitSize + 'M！');
                            return false;
                        }
                    }
                    if (type === "image") {
                        if (fileSize >= this.systemSet.imgLimitSize) {
                            toastMiddle('图片大小不要超过' + this.systemSet.imgLimitSize + 'M！');
                            return false;
                        }
                    }
                    return true;
                },
                //--------------------END------------------------
            },
        })
    }
</script>
</body>

</html>
